import { NextResponse } from 'next/server';
import { query } from '@/utils/db';
import { RowDataPacket } from 'mysql2/promise';
import jwt from 'jsonwebtoken';

/**
 * 获取我的需求列表API
 * GET /api/enterprise/resources/my-needs
 * 需要登录且为企业管理员
 */
export async function GET(request: Request) {
  try {
    // 1. 验证用户是否已登录
    const authHeader = request.headers.get('Authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 2. 解析token
    const token = authHeader.substring(7); // 去掉"Bearer "前缀
    const secret = process.env.JWT_SECRET || 'your-secret-key';
    
    let decodedToken;
    try {
      decodedToken = jwt.verify(token, secret);
    } catch (error) {
      return NextResponse.json(
        { success: false, message: '无效的令牌' },
        { status: 401 }
      );
    }

    // 3. 获取用户信息
    const userId = (decodedToken as any).id;
    
    // 4. 查询用户是否为企业管理员
    const userQuery = `
      SELECT u.id, u.is_company_admin, c.id as company_id 
      FROM users u 
      LEFT JOIN companies c ON u.id = c.admin_id
      WHERE u.id = ?
    `;
    const [userResult] = await query<RowDataPacket[]>(userQuery, [userId]);
    
    if (!userResult || !userResult.is_company_admin) {
      return NextResponse.json(
        { success: false, message: '只有企业管理员才能访问此功能' },
        { status: 403 }
      );
    }

    // 5. 查询企业的需求列表
    const needsQuery = `
      SELECT 
        id, title, description, type, tags, is_active, created_at, updated_at
      FROM enterprise_cooperation_needs
      WHERE company_id = ?
      ORDER BY created_at DESC
    `;
    
    const needsResult = await query<RowDataPacket[]>(needsQuery, [userResult.company_id]);
    
    // 处理需求数据
    const needs = needsResult.map(need => {
      return {
        id: need.id,
        title: need.title,
        description: need.description,
        type: need.type,
        tags: need.tags ? need.tags.split(',') : [],
        is_active: Boolean(need.is_active),
        created_at: need.created_at,
        updated_at: need.updated_at
      };
    });

    return NextResponse.json({
      success: true,
      needs
    });
  } catch (error) {
    console.error('获取需求列表失败:', error);
    return NextResponse.json(
      { success: false, message: '获取需求列表失败' },
      { status: 500 }
    );
  }
} 